<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select
          @change="selectStreet"
          v-model="query.street"
          placeholder="所属街道"
          class="handle-select mr10"
        >
          <el-option
            v-for="(item, index) in streetData"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button
          type="primary"
          class="handle-del mr10"
          @click="handleAdd"
          v-if="samPermissions.includes('village:scalemanager:save')"
          >添加</el-button
        >
        <el-button
          type="danger"
          class="handle-del mr10"
          @click="delAllSelection"
          v-if="samPermissions.includes('village:scalemanager:delete')"
          >删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="账号"
          align="center"
        ></el-table-column>

        <!-- <el-table-column
          prop="enctypePassword"
          label="密码"
          align="center"
        ></el-table-column> -->
        <el-table-column
          prop="streets"
          label="所属街道"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="manager"
          label="负责人姓名"
          align="center"
        ></el-table-column>

        <el-table-column label="账号状态" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.enableStatus == '0'
                  ? 'success'
                  : scope.row.enableStatus == '1'
                  ? 'danger'
                  : ''
              "
              >{{ scope.row.statusName }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="samPermissions.includes('village:scalemanager:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-if="
                scope.row.enableStatus == 1 &&
                  samPermissions.includes('village:scalemanager:update')
              "
              @click="handleEnable(scope.$index, scope.row)"
              >启用</el-button
            >
            <el-button
              type="text"
              v-if="
                scope.row.enableStatus == 0 &&
                  samPermissions.includes('village:scalemanager:update')
              "
              @click="handleStop(scope.$index, scope.row)"
              >停用</el-button
            >

            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="samPermissions.includes('village:scalemanager:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form ref="editForm" :model="editForm" label-width="auto">
        <el-form-item label="请选择街道">
          <div class="block">
            <el-select
              v-model="managerDistrictDTOList"
              multiple
              clearable
              placeholder="请选择街道"
            >
              <el-option
                v-for="(item, index) in streetData"
                :key="index"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="请输入账号">
          <el-input
            v-model="editForm.mobile"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="请输入密码">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="请再次输入密码">
          <el-input
            v-model="editForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="请输入负责人姓名">
          <el-input
            v-model="editForm.manager"
            type="text"
            placeholder="请输入负责人姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="editForm.memo"
            type="text"
            placeholder="备注"
          ></el-input>
        </el-form-item>

        <el-form-item label="">
          <template>
            <el-radio v-model="editForm.enableStatus" label="0">正常</el-radio>
            <el-radio v-model="editForm.enableStatus" label="1">停用</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="50%">
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="auto">
        <el-form-item label="请选择街道">
          <div class="block">
            <el-select
              v-model="managerDistrictDTOList"
              multiple
              placeholder="请选择街道"
            >
              <el-option
                v-for="(item, index) in streetData"
                :key="index"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="请输入账号">
          <el-input
            v-model="addForm.mobile"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="请输入密码" prop="password">
          <el-input
            v-model="addForm.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="请再次输入密码" prop="confirmPassword">
          <el-input
            v-model="addForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="请输入负责人姓名">
          <el-input
            v-model="addForm.manager"
            type="text"
            placeholder="请输入负责人姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="addForm.memo"
            type="text"
            placeholder="备注"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <template>
            <el-radio v-model="addForm.enableStatus" label="0">正常</el-radio>
            <el-radio v-model="addForm.enableStatus" label="1">停用</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import util from "utils/util";
import { mapGetters } from "vuex";
export default {
  name: "scaleadminmanage",
  data() {
    var validatePass = (rule, value, callback) => {
      console.log(rule, value, callback);
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.addForm.confirmPassword !== "") {
          this.$refs.addForm.validateField("confirmPassword");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      samPermissions: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
        street: ""
      },
      rules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          // {
          //   min: 6,
          //   max: 16,
          //   message: "长度在 6 到 16 个字符",
          //   trigger: "blur"
          // },
          { validator: validatePass, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          // {
          //   min: 6,
          //   max: 16,
          //   message: "长度在 6 到 16 个字符",
          //   trigger: "blur"
          // },
          { validator: validatePass2, trigger: "blur", required: true }
        ]
      },
      managerDistrictDTOList: [],
      tableData: [],
      streetId: "",
      streetData: [],

      delList: [],
      editVisible: false,
      addVisible: false,
      pageTotal: 0,
      editForm: {
        mobile: "",
        password: "",
        confirmPassword: "",
        manager: "",
        memo: "",
        enableStatus: "0"
      },
      addForm: {
        mobile: "",
        password: "",
        confirmPassword: "",
        manager: "",
        memo: "",
        enableStatus: "0"
      },
      idx: -1,
      id: -1
    };
  },
  created() {
    this.getSAMData();
    // 获取街道数据
    this.getStreetDate();
    this.samPermissions = this.permissions;
  },
  methods: {
    // 停用
    handleStop(index, row) {
      this.$confirm("确定要停用吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.editForm = {};
          this.managerDistrictDTOList = row.subDistrictList
            ? row.subDistrictList.map((item, index) => {
                return item.id;
              })
            : [];
          this.id = row.id;
          this.editForm.enableStatus = 1;
          this.saveEdit();
        })
        .catch(() => {});
    },
    // 启用
    handleEnable(index, row) {
      this.$confirm("确定要启用吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.editForm = {};
          this.managerDistrictDTOList = row.subDistrictList
            ? row.subDistrictList.map((item, index) => {
                return item.id;
              })
            : [];
          this.id = row.id;
          this.editForm.enableStatus = 0;
          this.saveEdit();
        })
        .catch(() => {});
    },

    valueChange(value) {
      console.log(value);
    },
    getStreetDate() {
      this.$axios
        .get("/village/subdistrict/page", {
          params: {
            parentId: 0
          }
        })
        .then(({ data: res }) => {
          console.log("街道数据", res);
          if (res.code != 0) {
            return;
          }
          this.streetData = res.data.list;
        })
        .catch(() => {});
    },
    selectStreet(streetId) {
      console.log("街道ID", streetId);
      this.streetId = streetId;
    },

    getSAMData() {
      this.$axios
        .get("/village/scalemanager/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,
            districtId: this.streetId
          }
        })
        .then(({ data: res }) => {
          console.log("称管理员管理", res);
          if (res.code != 0) {
            return;
          }
          res.data.list.map((item, index) => {
            item["enctypePassword"] = "******";
            item["streets"] = item.subDistrictList
              ? item.subDistrictList
                  .map(val => {
                    return val.name;
                  })
                  .join("、")
              : null;
            var pageIndex = this.query.pageIndex;
            item.index = index + 1 + (pageIndex - 1) * this.query.pageSize;
            if (item.enableStatus == 0) {
              item.statusName = "正常";
            } else if (item.enableStatus == 1) {
              item.statusName = "停用";
            }
          });
          this.tableData = res.data.list;
          this.pageTotal = res.data.total;
          this.streetId = "";
        })
        .catch(() => {});
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getSAMData();
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids = [];
      var ids = this.ids;
      ids[0] = row.id;
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    delete(ids) {
      this.$axios
        .delete("/village/scalemanager", {
          data: ids
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.ids = [];
          this.getSAMData();
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.ids = [];
      var ids = this.ids;
      val.forEach((item, index) => {
        ids.push(item.id);
      });
    },
    delAllSelection() {
      var ids = this.ids;
      ids = [...new Set(ids)];
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    // 新增操作
    handleAdd() {
      this.addVisible = true;
    },
    cancelAdd() {
      this.addVisible = false;
      this.managerDistrictDTOList = [];
      this.addForm = {
        mobile: "",
        password: "",
        confirmPassword: "",
        manager: "",
        memo: "",
        enableStatus: "0"
      };
    },
    saveAdd() {
      console.log(this.addForm);
      var bool = util.isEmpty(this.addForm);
      if (bool) {
        return this.$message.warning("必填项不能为空");
      }
      if (this.addForm.password !== this.addForm.confirmPassword) {
        return this.$message.warning("两次输入密码不一致");
      }

      this.$axios
        .post("/village/scalemanager", {
          manager: this.addForm.manager,
          mobile: this.addForm.mobile,
          password: this.addForm.password,
          managerDistrictDTOList: this.handleArray(this.managerDistrictDTOList),
          memo: this.addForm.memo,
          enableStatus: this.addForm.enableStatus
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code != 0) {
            return this.$message.success("添加成功");
          }
          this.addVisible = false;
          this.managerDistrictDTOList = [];
          this.addForm = {
            mobile: "",
            password: "",
            confirmPassword: "",
            manager: "",
            memo: "",
            enableStatus: "0"
          };
          this.getSAMData();
        })
        .catch(() => {});
    },
    handleArray(arr) {
      return arr.map((item, index) => {
        return { districtId: item };
      });
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.editVisible = true;
      this.id = row.id;
      // 获取编辑数据
      this.getEdit(row.id);
    },
    getEdit(id) {
      this.$axios
        .get(`/village/scalemanager/${id}`)
        .then(({ data: res }) => {
          console.log("编辑数据", res);
          if (res.code !== 0) {
            return;
          }
          this.editForm = {
            mobile: res.data.mobile,
            password: res.data.password,
            confirmPassword: res.data.password,
            manager: res.data.manager,
            memo: res.data.memo,
            enableStatus: res.data.enableStatus.toString()
          };
          this.managerDistrictDTOList = res.data.subDistrictList
            ? res.data.subDistrictList.map(val => {
                return val.id;
              })
            : [];
          console.log(this.editForm);
        })
        .catch(() => {});
    },
    // 保存编辑
    saveEdit() {
      console.log(this.editForm, this.managerDistrictDTOList);
      var bool = util.isEmpty(this.editForm);
      console.log(bool);
      if (bool || this.managerDistrictDTOList.length === 0) {
        return this.$message.warning("必填项不能为空");
      }
      this.$axios
        .put("/village/scalemanager", {
          id: this.id,
          mobile: this.editForm.mobile,
          password: this.editForm.password,
          manager: this.editForm.manager,
          memo: this.editForm.memo,
          enableStatus: this.editForm.enableStatus,
          managerDistrictDTOList: this.handleArray(this.managerDistrictDTOList)
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return;
          }
          this.editVisible = false;
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.managerDistrictDTOList = [];
          this.id = "";
          this.editForm = {
            mobile: "",
            password: "",
            manager: "",
            memo: "",
            enableStatus: "",
            confirmPassword: ""
          };
          this.getSAMData();
        })
        .catch(() => {});
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getSAMData();
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getSAMData();
    }
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    // "addForm.confirmPassword": function(newValue, oldValue) {
    //   console.log(newValue, oldValue);
    //   if (newValue != this.addForm.password) {
    //     this.$message.warning("密码不一致");
    //   }
    // },
    // "editForm.confirmPassword": function(newValue, oldValue) {
    //   console.log(newValue, oldValue);
    //   if (newValue != this.editForm.password) {
    //     this.$message.warning("密码不一致");
    //   }
    // },
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/scale-admin-manage") {
        this.samPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      this.samPermissions = newVal;
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 120px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
